/*
 * Antonio Canabrava Fraideinberze 7152292
 * Lucas Avelino Sodre Santos      7239086
 * Pedro Rael Garcia               7153021
 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <omp.h>
#include "avl.h"

int palindrome(char*);
int isspecial(char);
void palindromeInPhrase(char*);
void palindromeInWord(char*);

int
main(int argc, char* args[])
{
    char* text;

    if(argc < 2)
    {
        palindromeInWord("shakespe.txt");
        palindromeInPhrase("shakespe.txt");
    }

    else
    {
        palindromeInWord(args[1]);
        palindromeInPhrase(args[1]);
    }

    return 0;
}

int
palindrome(char *word)
{
    int i;
    int res = 0;
    int len = strlen(word);

    for(i = 0; i < len; i++)
        if(word[i] == word[len - i - 1])
            res++;

    if(res == len)
        return 1;

    else
        return 0;
}

int
isspecial(char c)
{
    if(c == ' ' || c == '\t' || c == '\v' || c == '\f' || c == '\r')
        return 1;

    else
        return 0;
}

void
palindromeInPhrase(char* text)
{
    FILE * pFile;
    long lSize;
    char * pch = 0;
    char * buffer;
    char * buffer2;
    size_t result;
    node *phrase = NULL;
    puts("\n\nAbrindo o arquivo texto....");
    pFile = fopen(text , "rb");

    if(pFile==NULL)
    {
        fputs("File error",stderr);
        exit(1);
    }

    // obtain file size:
    fseek(pFile, 0, SEEK_END);
    lSize = ftell(pFile);
    rewind(pFile);
    puts("Alocando memoria para o buffer principal....");
    // allocate memory to contain the whole file:
    buffer = (char*) malloc(sizeof(char) * lSize + 1);

    if(buffer == NULL)
    {
        fputs("Memory error",stderr);
        exit(2);
    }

    puts("Alocando memoria para o buffer auxiliar....");
    buffer2 = (char*) malloc(sizeof(char) * lSize + 1);

    if(buffer == NULL)
    {
        fputs("Memory error",stderr);
        exit(2);
    }

    // copy the file into the buffer:
    puts("Copiando arquivo para o buffer principal....");
    result = fread(buffer, 1, lSize, pFile);

    if(result != lSize)
    {
        fputs("Reading error",stderr);
        exit(3);
    }

    /* the whole file is now loaded in the memory buffer. */
    // Close pFile by now
    fclose(pFile);
    int i,j;
    //Size of buffer
    size_t b = lSize;
    //To previne garbage
    buffer[lSize] = '\0';
    //   puts(buffer);
    //Verify if is puntuation to break the text in phrases
    puts("Procurando por frases separadas por pontuacao....");

    for(i = 0; i < b; i++)
        if(ispunct(buffer[i]))
            buffer[i] = '\n';

    //Remove any spaces of the phrases
    puts("Removendo espacos de frases encontradas....");
    j = 0;

    for(i = 0; i < b; i++)
        if(!isspecial(buffer[i]))
        {
            buffer2[j] = tolower(buffer[i]);
            j++;
        }

    //Verify palindromes in phrases
    puts("Verificando os palindromos....");
    pFile = fopen("res_phrase.txt", "w");
    pch = 0;
    pch = strtok(buffer2, "\n");

    while(pch != NULL)
    {
        if((find(pch,phrase) == NULL) && palindrome(pch))
        {
            phrase = insert(pch, phrase);
            fprintf(pFile, "%s\n", pch);
        }

        pch = strtok(NULL, "\n");
    }

    puts("Limpando a memoria...,\n palindromos encontrados estao no arquivo res_phrase.txt....");
    free(buffer);
    free(buffer2);
    fclose(pFile);
    return;
}

void
palindromeInWord(char* text)
{
    FILE * pFile;
    long lSize;
    char * buffer;
    size_t result;
    int i;
    char *pch;
    puts("Abrindo o arquivo texto para procurar palavras....");
    pFile = fopen(text , "rb");

    if(pFile==NULL)
    {
        fputs("File error",stderr);
        exit(1);
    }

    // obtain file size:
    fseek(pFile, 0, SEEK_END);
    lSize = ftell(pFile);
    rewind(pFile);
    // allocate memory to contain the whole file:
    puts("Alocando memoria para o buffer principal....");
    buffer = (char*) malloc(sizeof(char) * lSize + 1);

    if(buffer == NULL)
    {
        fputs("Memory error",stderr);
        exit(2);
    }

    // copy the file into the buffer:
    puts("Copiando arquivo para o buffer principal....");
    result = fread(buffer, 1, lSize, pFile);

    if(result != lSize)
    {
        fputs("Reading error",stderr);
        exit(3);
    }

    /* the whole file is now loaded in the memory buffer. */
    // terminate
    fclose(pFile);
    //Size of buffer
    size_t b = lSize;
    //To previne garbage
    buffer[lSize] = '\0';
    //   puts(buffer);
    puts("Separando o texto por palavras....");

    for(i = 0; i < b; i++)
    {
        buffer[i] = tolower(buffer[i]);

        if(ispunct(buffer[i]) || isspace(buffer[i]))
            buffer[i]='\n';
    }

    puts("Verificando os palindromos....");
    node *words = NULL;
    pFile = fopen("res_word.txt", "w");
    pch = strtok(buffer, "\n");

    while(pch != NULL)
    {
        if(find(pch,words) == NULL && palindrome(pch))
        {
            words = insert(pch, words);
            fprintf(pFile, "%s\n", pch);
        }

        pch = strtok(NULL, "\n");
    }

    puts("Limpando a memoria...,\n palindromos encontrados estao no arquivo res_word.txt....");
    free(buffer);
    fclose(pFile);
    return;
}
